var showcomplete=null;
var ws;
var ws_active = false;
var GLOBAL_SOCKET_CONNECT_ID = Math.random();

function getInfo()
{
  	var parseBid = setInterval(function(){
      parseDataAction();
    },1000);
    ws = new MyWebSocket("35.188.87.77:9501",{
      params: {
        JCONNECTID : GLOBAL_SOCKET_CONNECT_ID,
        ids:$('#ids').val()
      },
      onmessage: function (res) {
        console.log(res.data);
        updateGoods(res.data);
      },
      onopen: function() {
        console.log("SOCKET已连接上..");
      },
      onclose: function() {
        time_wran('与服务器的连接已经断开','<h3 style="padding:10px;">与服务器的连接暂时中断,无法得到实时竞拍数据，请联系客服400-343-5436。</h3>');
        console.log("SOCKET连接已中断!");
      },
      onerror: function(err) {
        time_wran('与服务器的连接已经断开','错误提示：'+err);
        console.log(err);
      }
    });
    
}
function updateGoods(res){
  var json = JSON.parse(res);
  var list = JSON.parse($("#goods_list").val());
  var temp_list = {};
  var temp_ids = '-';
  for(j in json){
    var id = parseInt(json[j].id);
    if(id>0){
      temp_ids+='-'+id;
      temp_list['goods'+id] = json[j];
    }
  }
  temp_ids +='--';
  for(i in list){
    if(temp_ids.indexOf('-'+list[i].id+'-')>0){
      list[i] = temp_list['goods'+list[i].id];
    }
  }
  $("#goods_list").val(JSON.stringify(list));
}
//当前围观人数
function cuser(gids)
{
    $.post(site_root+"/tools/currentcount.php",{gid:gids,'rand':Math.random() },
       function(data){
            $("#ccuser_"+gids).html(data);
       } 
    ); 
    setTimeout(function(){cuser(gids);},60000);
}
function parseDataAction()
{
    var obj = JSON.parse($("#goods_list").val());
	if(obj.length>0)
	{
		for(i in obj)
		{
            if(obj[i]['lasttime']>0){
              var oldprice = parseFloat($('#nowprice_'+obj[i].id).html()).toFixed(2);
              var nowprice = parseFloat(obj[i].nowprice).toFixed(2);
              
              if(oldprice > 0 && nowprice-oldprice > 0.01)
              {
                  changcolor('nowprice_'+obj[i].id);
              }
              $('#lasttime_'+obj[i].id).html(diffTime(obj[i].lasttime));
              $('#currentuser_'+obj[i].id).html(obj[i].currentuser);
              $('#nowprice_'+obj[i].id).html(nowprice);
              var avatar = $('#avatar_'+obj[i].id);

              if(avatar.attr('src')!=null && obj[i].currentuid>0 && obj[i].currentuid!=avatar.attr('data-uid'))
              {
                  avatar.attr('data-uid',obj[i].currentuid);
                  avatar.attr('src',"/tools/avatar.php?uid="+obj[i].currentuid+"&size=middle&type=virtual");
              }
              if(obj[i].lasttime<10 && obj[i].lasttime>=0)
              {
                  $('#lasttime_'+obj[i].id).attr('class','red');
              }
              else
              {
                  $('#lasttime_'+obj[i].id).attr('class','green');
              }
            }
            obj[i]['lasttime'] = parseInt(obj[i]['lasttime']) - 1;
		}
        $("#goods_list").val(JSON.stringify(obj));
	}

}

function checkcomplete()
{
	complete=0;
	moids=$('#oids').val().split('-');
	
	showcomplete=setTimeout(function(){checkcomplete();},1000);
	if($('#ids').val()=='')
	{
		for(o in moids)
		{
			$('#lasttime_'+moids[o]).html('竞拍已成交');
			$('#bid_'+moids[o]).addClass('bidcompletebutton');
			$('#bid_'+moids[o]).addClass('reccompletebutton');
		}
		Complete_Dialog();
		clearTimeout(showcomplete);
	}
	else
	{
		nids='-'+$('#ids').val()+'-';
		
		for(o in moids)
		{
			if(nids.indexOf('-'+moids[o]+'-')<0)
			{
				$('#lasttime_'+moids[o]).html('竞拍已成交');
				$('#bid_'+moids[o]).addClass('bidcompletebutton');
				$('#bid_'+moids[o]).addClass('reccompletebutton');
				complete++;
			}
		}
		if(complete>0)
		{
			Complete_Dialog();
			clearTimeout(showcomplete);
		}
	}
	
}
function setInfo(id)
{
	$.post(site_root+"?con=order&act=bid",{ goods_id:id,'rand':Math.random() },
		   function(data){
			if(data.code == 0)
			{
                var dataobj = data.data
				$('#currentuser_'+dataobj.id).html(dataobj.currentuser);
				$('#nowprice_'+dataobj.id).html(parseFloat(dataobj.nowprice).toFixed(2));
				myoldbidcount=$('#mybidcount').html();
				
				if(myoldbidcount>0)
				{
					$('#mybidcount').html(myoldbidcount*1+1);
				}
				else
				{
					$('#mybidcount').html('1');
				}
				$('#myremainb').html(parseFloat($('#myremainb').html())-parseFloat($('#diffmoney').html()));
				changcolor('nowprice_'+dataobj.id);
                var res = {};
              	res.type='bid';
                res.data = [];
                res.data.push(data.data);
				ws.send(res);
                updateGoods('['+JSON.stringify(data.data)+']');
			} else if(data.code == -1){
              if(data.data && data.data.datastatus && data.data.datastatus=='nologin')
              {
                  Login_Dialog();
              }
              else 
              {
                  $("#toast").text(data.msg);
				  $("#toast").fadeIn().delay(3000).fadeOut();
              }
            }
			
		   },'json'
		); 
		
}
//隐藏
var idh=0;
function hidid(id)
{
	if(idh>0)
	{
		idh=0;
		$('#'+id).hide('slow');
	}
	else
	{
		idh++;
		setTimeout(function(){hidid(id);},3000);
	}
	
}
//出价记录
function getBuyLog(id,dotype,logstop,ordertype,showid)
{
	var ids=$('#ids').val();
	if(ids!='' && active<alerttime)
	{
		$.post(site_root+"/tools/getbuylog.php?rand="+Math.random(),{ goods_id:id, order:ordertype},
         function(data){
          if(data && data.code == 0)
          {
            parseDataLogAction(data,showid);
          }
        }, 'json'
       ); 
	}
	if(!logstop)
	{
		setTimeout(function(){getBuyLog(id,dotype,logstop,ordertype,showid);},10000);
	}
}
function parseDataLogAction(dataobj,showid)
{
	var obj=dataobj.data;
	var str='';
	switch(showid)
	{
		case 'saleLog':
			for(i in obj)
			{
				str+='<li style=""> <span class="a"></span> <span id="luname_1" class="uesrname" title="'+obj[i].username+'">'+obj[i].username+'</span> <span id="lip_1" class="ip grayB4">'+obj[i].ip+'</span> <span class="lmobile grayB4" id="lmobile_1" title="'+obj[i].address+'">'+obj[i].address+'</span> <span class="price red"> <span id="lprice_1">￥'+obj[i].price+'</span> </span> </li>';
			}
		break;
		case 'countLog':
			list=['a','b','c','d'];
			for(i in obj)
			{
				s=i<4?list[i]:'d';
				str+='<li> <span class="'+s+'">'+(i*1+1)+'</span> <span title="tfadd" id="runame_1" class="uesrname">'+obj[i].username+'</span> <span id="rmobile_1" class="ip grayB4">'+obj[i].ip+'</span> <span class="price grayB4"> <span title="'+obj[i].address+'" id="rcost_1">'+obj[i].address+'</span> </span> </li>';
			}
		break;
	}
	$('#'+showid+'_'+dataobj.gid).html(str);
}
//添加聊天内容
function setChat(id,mcontent,goodsname,facenum)
{
	if(mcontent)
	{
		$.post(site_root+"/tools/setchat.php",{ gid:id,content:mcontent,gname:goodsname,face:facenum,'rand':Math.random() },
			   function(data){
				if(data)
				{
				    eval('var dataobj='+data);
					if(dataobj.datastatus=='success')
					{
						if(dataobj.ispassed>0)
						{
							$('#msgerror').show()
							$('#msgerror').html('留言审核后显示');
						}
						else
						{
							$('#msgerror').show()
							if(dataobj.data[0].dmoney>0)
							{
								$("#kb_tips").animate({top:200,opacity: 'toggle'},"slow"); 
								$("#kb_tips").hide(1000); 
								$('#msgerror').html('留言成功,扣除金币'+dataobj.data[0].dmoney);
							}
							else
							{
								$('#msgerror').html('留言成功');
							}
							parseChatAction(dataobj,true);
						}
					}
					else if(dataobj.datastatus=='nomoney')
					{
						$('#msgerror').show()
						$('#msgerror').html('余额不足');
					}
					
					else if(dataobj.datastatus=='failed')
					{
						$('#msgerror').show()
						$('#msgerror').html('留言失败');
					}
					else if(dataobj.datastatus=='nologin')
					{
						$('#msgerror').show()
						$('#msgerror').html('用户未登录');
					}
					else if(dataobj.datastatus=='nouser')
					{
						$('#msgerror').show()
						$('#msgerror').html('用户不存在');
					}
				}
			   } 
			);
	}
	else
	{
		$('#msgerror').show()
		$('#msgerror').html('内容不能为空');
		
	}
	setTimeout(function(){$('#msgerror').hide();},1000);
}
//聊天内容
function getChat(id,dotype,showgoods)
{
	var ids=$('#ids').val();
	if(ids!='' && active<alerttime)
	{
      $.post(site_root+"/tools/getchat.php",{ gid:id,'rand':Math.random() },
      function(data){
        if(data.code == 0)
        {
          parseChatAction(data,false,showgoods);
        }
      },'json'
     ); 
	}
	setTimeout(function(){getChat(id,dotype,showgoods);},30000);
}
function parseChatAction(dataobj,append,showgoods)
{
							
	$('#divChatList').animate({scrollTop:100000});
	var obj=dataobj.data;
	var str='';
	for(i in obj)
	{
		if(obj[i].issystem>0)
		{
			
			str+='<div id="chatitem_'+obj[i].id+'" class="chatitem chatitemsys" style="float:left;"><div class="systxt"><div style="float:left"><span class="sysname red">系统消息：</span>'+obj[i].content+'</div><div class="sysaddtime">'+obj[i].updatetime+'</div></div></div>';
		}
		else
		{
			str+='<div class="chatitem" id="chatitem_'+obj[i].id+'"><div class="u"><img height="13" width="13" align="absmiddle" class="chatavatar" src="/tools/avatar.php?uid='+obj[i].uid+'&size=small&type=virtual"> <span class="username blue">'+obj[i].username+'：</span></div><div class="chatitem_emo_other"><div class="emoshape"></div><div class="emotxt">'+obj[i].content+'<div class="emotime">'+obj[i].updatetime+'</div></div></div></div>';
		}
	}
	if(append)
	{
		$('#divChatList').append(str);
	}
	else
	{
		$('#divChatList').html(str);
	}
	
}
function diffTime(Diffms)
{
	DifferHour = Math.floor(Diffms / 3600)
	Diffms -= DifferHour * 3600
	DifferMinute = Math.floor(Diffms/60)
	Diffms -= DifferMinute * 60
	DifferSecond=Diffms
	if(DifferHour<10)
	{
		DifferHour='0'+DifferHour;
	}
	if(DifferMinute<10)
	{
		DifferMinute='0'+DifferMinute;
	}
	if(DifferSecond<10)
	{
		DifferSecond='0'+DifferSecond;
	}
	return DifferHour+':'+DifferMinute+':'+DifferSecond;
}
function normal_time(Diffms,id,stext)
{
	var starttime=new Date(Diffms).getTime();
	var ndate=new Date().getTime();
	diff=starttime-ndate;
	if(diff>0)
	{
		var day=Math.floor(diff/(1000*60*60*24));
		var hour=Math.floor(diff/(1000*60*60))%24;
		var minute=Math.floor(diff/(1000*60))%60;
		var second=Math.floor(diff/1000)%60;
		str=hour+"小时"+minute+"分"+second+"秒";
		if(day>0)
		{
			str=day+"天"+str;
		}
		$('#'+id).html(str);
	}
	else
	{
		$('#'+id).html(stext);
	}
	

	setTimeout(function(){normal_time(Diffms,id,stext);},1000);
}
//测试速度
function testspeed()
{
	if(active<alerttime)
	{
		$.post(site_root+"/tools/testspeed.php",{'rand':Math.random() },
			   function(data){
				data=parseInt(data);
				if(data>300 || data==0)
				{
					$('#imgSpeed').addClass('speed01');
				}
				else if(data>100 && data<300)
				{
					$('#imgSpeed').addClass('speed02');
				}
				else if(data>0 && data<100)
				{
					$('#imgSpeed').addClass('speed04');
				}
				else
				{
					$('#imgSpeed').addClass('speed00');
				}
			   } 
		);
	}
	setTimeout(function(){testspeed();},10000);
}

//微秒
var mti=8;
function domicrotime(obj)
{
	$('#lasttime_'+obj).html($('#lasttime_'+obj).html()+'.'+mti);
	if(mti>0)
	{
		mti--;
		
	}
	else
	{
		mti=8;
	}
}
//价格闪光
colori=0;
function changcolor(id){
	color=['#F60E2E','#F53752','#F46F82','#F7AAB4','#fff'];
	$('#'+id).css('background-color',color[colori]);
	if(colori<5)
	{
		setTimeout(function(){changcolor(id)},50);
		colori++;
	}
	else
	{
		colori=0;
	}
}
//警告
var lock=0;
function show_alert()
{
	if(active<alerttime)
	{
		active++;
	}
	else if(active>=alerttime)
	{
      
		time_wran('您超过5分钟未进行任何操作。',$('#dialog_wran').html());
		lock=1;
	}
	setTimeout('show_alert()',1000);
}

function continue_alert()
{
	active=1;
	lock=0;
}

document.onmousemove=function()
{
	if(lock==0)
	{
		active=1;
	}
}